import type { Request } from 'express';
import { MoreThan } from 'typeorm';
import {
  responseSuccess,
  responseData,
} from '@/share/interface/standard';
import { RelationShipController } from '@/controller/miniProgram/UserController';
import Base from '@/controller/public/MiniBaseController';

export class MonitorController extends Base {
  async getUserCount() {
    const user = await this.userRepository.find();
    return responseSuccess(user.length);
  }

  async getUserVisitCount() {
    const users = await this.userRepository.find();
    if (users.length === 0) {
      return responseSuccess(0);
    }
    const count = users.reduce((total, user) => {
      const user_visit_list = JSON.parse(user.visit_list || '[]');
      const visitCount = user_visit_list.reduce(
        (sum, visit) => sum + (visit.count || 0),
        0
      );
      return total + visitCount;
    }, 0);
    return responseSuccess(count || 0);
  }

  async getUserVisitCountForDays(req: Request) {
    function subtractDays(date: Date, days: number): Date {
      const result = new Date(date);
      result.setDate(result.getDate() - days);
      return result;
    }

    const daysBack = parseInt(req.query.day) || 7; // 如果没有提供查询参数，默认为7天
    const endDate = new Date(); // 当前日期
    const startDate = subtractDays(endDate, daysBack); // 当前日期前n天的日期

    const users = await this.userRepository.find();
    if (users.length === 0) {
      return responseSuccess(0);
    }
    const visitCountsByDay = new Map<string, number>();
    users.forEach((user) => {
      // 确保 visit_list 存在且不为空
      const user_visit_list = JSON.parse(user.visit_list || '[]');
      if (user_visit_list && user_visit_list.length > 0) {
        // 遍历每个用户的访问记录
        user_visit_list.forEach((visit) => {
          // 解析 visit.date 并转换为本地日期对象，以便比较
          const visitDate = new Date(visit.date);

          // 确保访问记录的日期在指定日期范围内
          if (visitDate >= startDate && visitDate <= endDate) {
            // 将日期格式化为 'YYYY-MM-DD' 格式，以便在 Map 中使用
            const formattedDate = visitDate
              .toISOString()
              .split('T')[0];

            // 如果该日期已经在 Map 中，则累加计数；否则初始化为 visit.count
            visitCountsByDay.set(
              formattedDate,
              (visitCountsByDay.get(formattedDate) || 0) + visit.count
            );
          }
        });
      }
    });

    // 将 Map 转换为期望的数组格式 [['2019-10-10', 200], ...]
    const result = Array.from(visitCountsByDay.entries())
      .map(([date, count]) => [date, count])
      .sort(
        (a, b) => new Date(a[0]).getTime() - new Date(b[0]).getTime()
      ); // 添加这一行进行排序

    return responseSuccess(
      result.length
        ? result
        : [[new Date().toISOString().split('T')[0], 0]]
    );
  }

  async getUserIncreaseCount(req: Request) {
    const { day = 7 } = req.query;
    // 默认7天内新增加的用户
    const seven_days_ago = new Date();
    seven_days_ago.setDate(seven_days_ago.getDate() - day);

    const user = await this.userRepository.find({
      where: {
        created: MoreThan(seven_days_ago),
      },
      order: {
        created: 'DESC',
      },
    });

    return responseData({
      code: 0,
      msg: `用户增长数量(${day}天内)`,
      data: user,
    });
  }

  async getUserModuleClickCount() {
    const users = await this.userRepository.find({
      relations: ['module_data'],
      select: ['module_data', 'id'],
    });
    if (users.length === 0) {
      return responseSuccess(0);
    }
    const module_data = new Map<string, number>();
    users.forEach((user) => {
      if (user.module_data && user.module_data.length > 0) {
        user.module_data.forEach((module) => {
          module_data.set(
            module.module_name,
            (module_data.get(module.module_name) || 0) +
              module.module_visit
          );
        });
      }
    });

    const result = Array.from(module_data, ([key, value]) => ({
      value,
      name: key,
    }));

    return responseSuccess(result);
  }

  // 自定义模块点击量+1
  async addModuleClick(req: Request) {
    const { module_name, user_id = req.user_id } = req.body;
    return req.addModuleClick({ module_name, user_id });
  }

  // 获取预警人数
  async getWarningUser() {
    const users = await this.userRepository.find({
      relations: ['daily_health'],
      select: [
        'daily_health',
        'id',
        'nick_name',
        'initial_resting_heart_rate',
      ],
      order: {
        daily_health: {
          created: 'DESC',
        },
      },
    });
    let warning_user_count = 0;
    if (users.length === 0) {
      return responseSuccess(warning_user_count);
    }
    let message = [];

    for (let user of users) {
      // 1. 三天体重的差值大于2kg
      // 2. 静息心率对比初始心率增加＞15次
      // 3. 出现症状
      const health = user.daily_health[0]; // 今日健康
      //  user.daily_health[0] 是否是今天
      if (!health) continue;

      const today_health = new Date(health.created).getDate();
      const today = new Date().getDate() === today_health;
      if (!today) continue;
      if (health.today_status === 1) {
        warning_user_count++;
        message.push(user.nick_name + '- 今日症状标红');
      } else if (
        user.daily_health[2] &&
        (health.today_weight - user.daily_health[2].today_weight >
          2 ||
          health.today_weight - user.daily_health[1].today_weight > 2)
      ) {
        warning_user_count++;
        message.push(user.nick_name + '- 三天体重的差值大于2kg');
      } else if (
        health.today_resting_heart_rate -
          user.initial_resting_heart_rate >
        15
      ) {
        warning_user_count++;
        message.push(
          user.nick_name + '- 静息心率对比初始心率增加＞15次'
        );
      }
    }
    // 过滤掉相同的
    message = Array.from(new Set(message));
    return responseSuccess(warning_user_count, 0, message.join(','));
  }
  // 获取用户是否预警
  async getWarningUserOne(req: Request) {
    let user = await this.userRepository.findOne({
      where: { id: req.user_id },
      relations: ['daily_health'],
      select: [
        'daily_health',
        'id',
        'nick_name',
        'initial_resting_heart_rate',
        'role',
      ],
      order: {
        daily_health: {
          created: 'DESC',
        },
      },
    });
    let message = [];
    // 不等于患者
    if (user.role !== 'patient') {
      const relation_ship = new RelationShipController();
      const { data } = await relation_ship.getAllRelationListForUser(
        req
      );
      if (data.length === 0) return responseSuccess(false);
      user = { ...(data[0] || null) };
    }

    // 1. 三天体重的差值大于2kg
    // 2. 静息心率对比初始心率增加＞15次
    // 3. 出现症状
    const health = user.daily_health[0]; // 今日健康
    //  user.daily_health[0] 是否是今天
    if (!health) return responseSuccess(false);
    const today_health = new Date(health.created).getDate();
    const today = new Date().getDate() === today_health;
    if (!today) return responseSuccess(false);

    if (health.today_status === 1) {
      message.push(user.nick_name + '- 今日症状标红');
    } else if (
      user.daily_health[2] &&
      (health.today_weight - user.daily_health[2].today_weight > 2 ||
        health.today_weight - user.daily_health[1].today_weight > 2)
    ) {
      message.push(user.nick_name + '- 三天体重的差值大于2kg');
    } else if (
      health.today_resting_heart_rate -
        user.initial_resting_heart_rate >
      15
    ) {
      message.push(
        user.nick_name + '- 静息心率对比初始心率增加＞15次'
      );
    }
    if(message.length === 0) return responseSuccess(false);
    // 过滤掉相同的
    return responseSuccess(true, 0, message.join(','));
  }

  // 测试用接口
  async addVisitRecord(req: Request) {
    const { date, count, user_id } = req.body;
    const user = await this.userRepository.findOne({
      where: {
        id: user_id,
      },
    });
    if (!user) return responseSuccess('不存在用户');
    const user_visit_list = JSON.parse(user.visit_list || '[]');
    let visitRecordForToday = user_visit_list.find(
      (record: { date: string; count: number }) =>
        new Date(date).getDate() === new Date(record.date).getDate()
    );

    if (visitRecordForToday) {
      // 如果今天已经有记录，则计数++
      visitRecordForToday.count += count;
    } else {
      user_visit_list.push({
        date: new Date(date).toISOString(),
        count: count,
      });
    }

    await this.userRepository.update(user.id, {
      ...user,
      visit_list: JSON.stringify(user_visit_list),
    });

    const updatedUser = await this.userRepository.findOne({
      where: { id: user_id },
    });
    return responseSuccess(updatedUser);
  }
}
